package com.dcjt.firehotcarpad.moudle

import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.InputType
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.widget.Toast
import com.aries.library.fast.manager.LoggerManager
import com.aries.library.fast.util.SPUtil
import com.aries.library.fast.util.SizeUtil
import com.aries.library.fast.util.ToastUtil
import com.aries.ui.view.radius.RadiusEditText
import com.aries.ui.view.title.TitleBarView
import com.aries.ui.widget.alert.UIAlertView
import com.aries.ui.widget.progress.UIProgressView
import com.dcjt.firehotcarpad.R
import com.dcjt.firehotcarpad.base.ApiPath
import com.dcjt.firehotcarpad.base.ApiPath.REQUEST_CODE
import com.dcjt.firehotcarpad.base.ApiPath.RESULT_CODE
import com.dcjt.firehotcarpad.base.SPConstant
import com.dcjt.firehotcarpad.utils.LoginUtil
import com.dcjt.firehotcarpad.utils.StringUtils
import com.juntu.loginlib.contact.LoginConstant
import com.juntu.loginlib.ui.BaseLoginActivity
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_login.*

class LoginActivity : BaseLoginActivity() {

    private lateinit var dialog: UIProgressView
    private var isTokenOld: Boolean = false

    override fun initView(savedInstanceState: Bundle?) {

        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        findViewById<TitleBarView>(R.id.titleBar_headFastLib).visibility = View.GONE
        ret_passwordLogin.isSelected = true
        dialog = UIProgressView(this@LoginActivity, UIProgressView.STYLE_WEI_BO).setMessage("登录中...")
        dialog.setCancelable(false)
        ret_passwordLogin.setText(SPUtil.get(this@LoginActivity, SPConstant.CAR_CONFIG_NAME, "请配置车辆信息")as String)
        trv_login.setOnClickListener { login() }
        tv_set.setOnClickListener {
            shouManagerPW()
        }
        ret_passwordLogin2.setText(com.juntu.loginlib.util.LoginUtil.getStr(LoginConstant.USER_PSW))
        startFloatingButtonService()

        isTokenOld  = intent.getBooleanExtra("isTokenOld", false)
        if (isTokenOld){
            trv_login.performClick()
        }
    }

    private fun shouManagerPW() {
        val alertEdit = UIAlertView(this)
        val editText = RadiusEditText(this@LoginActivity)
        editText.getDelegate()
            .setTextColor(Color.GRAY)
            .setRadius(6f)
            .setBackgroundColor(Color.WHITE)
            .setStrokeColor(Color.GRAY)
            .setStrokeWidth(SizeUtil.dp2px(0.5f))
        editText.setMinHeight(SizeUtil.dp2px(40F))
        editText.setGravity(Gravity.CENTER_VERTICAL)
        editText.setPadding(SizeUtil.dp2px(12F), 0, SizeUtil.dp2px(12F), 0)
        editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14F)
        editText.setHint("请输入内容")
        editText.setText(
            "119"
        )
        editText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
        alertEdit.setMessage("若密码错误,无法进行下一步操作")
            .setMessageTextColor(this.resources.getColor(R.color.redText))
            .setPositiveButtonTextColor(this.resources.getColor(R.color.redText))
        alertEdit.setTitle("密码验证")
            .setPositiveButton("确认",
                DialogInterface.OnClickListener { dialog, which ->
                    val pw: String = editText.getText().toString().trim()
                    if (StringUtils.isEmpty(pw)) {
                        return@OnClickListener
                    }
                    if (pw.equals("119")) {
                        this@LoginActivity.startActivityForResult(Intent( this@LoginActivity,CarConfigActivity::class.java),REQUEST_CODE)
//                        FastUtil.startActivity(this,CarConfigActivity::class.java)
                    } else {
                        ToastUtil.show("请输入正确密码")
                        return@OnClickListener
                    }
                })
            .setNegativeButton("取消", null)
            .setView(editText)
            .show()
        editText.requestFocus()
    }

    override fun startMainActivity() {
        startActivity(Intent(this, NewMainActivity::class.java))
        finish()
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE && resultCode == RESULT_CODE){
            ret_passwordLogin2.setText(com.juntu.loginlib.util.LoginUtil.getStr(LoginConstant.USER_PSW))
            ret_passwordLogin.setText(SPUtil.get(this@LoginActivity, SPConstant.CAR_CONFIG_NAME, "请配置车辆信息")as String)
        } else if (requestCode == ApiPath.REQ_MANAGE_OVERLAY_PERMISSION) {
            if (!Settings.canDrawOverlays(this)) {
                Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun parseConfig(config: String?) = LoginUtil.parseConfigData(config)
    private fun startFloatingButtonService() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
            ToastUtil.show("请开启悬浮窗权限")
            startActivityForResult(
                    Intent(
                            Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                            Uri.parse("package:$packageName")
                    ), 0
            )
        }

    }

    private fun login() {

        val account: String = ret_passwordLogin.text.trim().toString()
        val password: String = ret_passwordLogin2.text.trim().toString()
        if (account.isEmpty() || password.isEmpty()) {
            ToastUtil.show("账号或密码不能为空")
            return
        }
        var id = SPUtil.get(this@LoginActivity, SPConstant.CAR_CONFIG_ID, "")as String
        if (StringUtils.isEmpty(id)){
            ToastUtil.show("请于左上角配置车辆信息")
            return
        }
        AndPermission.with(this)
            .runtime()
            .permission(
                *Permission.Group.STORAGE,
                *Permission.Group.LOCATION,
                Permission.CAMERA,
                Permission.RECORD_AUDIO/*,
                Permission.READ_PHONE_STATE*/
            )
            .onGranted {
                com.juntu.loginlib.util.LoginUtil.saveSp(LoginConstant.REMEMBER_PSW, cb_login.isChecked)
                com.juntu.loginlib.util.LoginUtil.saveSp(LoginConstant.USER_PSW, password!!)

                if (cb_login.isChecked){
                    com.juntu.loginlib.util.LoginUtil.saveSp(LoginConstant.USER_NAME, id!!)
                    com.juntu.loginlib.util.LoginUtil.saveSp(LoginConstant.DEVICE_TYPE,"CZPB")
                    com.juntu.loginlib.util.LoginUtil.saveSp(LoginConstant.PLACE_ID,"YDZHC")
                }
                doLogin(id!! ,password!!,"CZPB","YDZHC")

                val sp = application.getSharedPreferences(
                    application.packageName,
                    Context.MODE_PRIVATE
                )
                LoggerManager.e("设备编号1："+sp.getString(LoginConstant.DEVICE_ID, ""))


            }
            .onDenied {
                ToastUtil.show("你拒绝了一些必要的权限，可能造成应用某些功能不可用")
                trv_login.performClick()
            }
            .start()


    }

    override fun getLayoutId(): Int = R.layout.activity_login

    override fun saveLoginInfo(loginResult: String?) = LoginUtil.parseLoginResult(loginResult)

    override fun showDialog(msg: String?) {

        runOnUiThread(Runnable {
            //更新UI
            dialog.setMessage(msg)
            if (msg!!.contains("正在登录")){
                dialog.show()
            }else{
                ToastUtil.show(msg)
            }
        })
    }

    override fun dismissDialog() {
        dialog.dismiss()
    }


}
